
/**
 * copyright(c) 2013 www.jiongshibaoliao.com, All Rights Reserved.
 * project: jiongshibaoliao 
 * author: 曾帅
 * date: 2014-1-9 下午04:57:21
 * version: v1.0
 */

package com.jiongshibaoliao.web;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.jiongshibaoliao.common.constants.ErrorCode;
import com.jiongshibaoliao.common.mybatis.Page;
import com.jiongshibaoliao.common.mybatis.PageBean;
import com.jiongshibaoliao.exception.JiongException;
import com.jiongshibaoliao.model.Article;
import com.jiongshibaoliao.model.Comment;
import com.jiongshibaoliao.model.bean.UserBean;
import com.jiongshibaoliao.model.enums.Audit;
import com.jiongshibaoliao.service.ArticleService;
import com.jiongshibaoliao.service.CommentService;
import com.jiongshibaoliao.service.UserService;

/**
 * @project jiongshibaoliao
 * @author 曾帅 
 * @version 1.0
 * @date 2014-1-9 下午04:57:21   
 */

@Controller
public class ArticleController extends BaseController {

	private static final Logger logger = Logger.getLogger(ArticleController.class);
	
	@Autowired
	public ArticleService articleService;
	
	@Autowired
	public UserService usereService;
	
	@Autowired
	public CommentService commentService;
	
	@RequestMapping(value = "/article/new", method = { RequestMethod.GET, RequestMethod.POST })
	public String newArticle(HttpServletRequest request, ModelMap model) {

		return "newArticle";
	}
	
	@RequestMapping(value = "/article/create", method = { RequestMethod.GET, RequestMethod.POST })
	public String create(Article article, @RequestParam MultipartFile imgFile, HttpServletRequest request, ModelMap model) {
		if(article == null || article.getContent() == null) {
			model.put("errCode", ErrorCode.CODE_10001);
			return "newArticle";
		}
		if(imgFile != null && imgFile.isEmpty() == false) {
			String imgPath = "articleImg/";
			String suffix = imgFile.getOriginalFilename().substring(imgFile.getOriginalFilename().lastIndexOf("."));
			String fileName = UUID.randomUUID() + suffix;
			File file = new File(request.getSession().getServletContext().getRealPath("/" + imgPath), fileName);
			try {
				FileUtils.copyInputStreamToFile(imgFile.getInputStream(), file);
			} catch (IOException e) {
				logger.error("imgFile upLoad failure：", e);
				model.put("errMsg", "真相上传失败，请您重试！");
				return ERROR;
			}
			article.setImgPath(imgPath + fileName);
		}
		
		String clientIp = super.getClientIp(request);
		article.setUpLoadIp(clientIp);
		UserBean userBean = super.sessionUser(request);
		if(userBean != null) {
			article.setUserId(usereService.getUserIdByLoginName(userBean.getLoginName()));
		}
		
		articleService.create(article);
		logger.info("article publish success, clientIp=" + clientIp);
		model.put("successMsg", "囧事发表成功，请等待审核通过！去囧事爆料首页：<a href=\"/\">首页</a>， 继续发表：<a href=\"/article/new\">吐槽囧事</a>");

		return SUCCESS;
	}
	
	@RequestMapping(value = "/article/audit", method = { RequestMethod.GET, RequestMethod.POST })
	public String audit(HttpServletRequest request, ModelMap model) {
		UserBean userBean = super.sessionUser(request);
		Article article = articleService.getUNAuditRandom(super.getClientIp(request), userBean == null ? null : usereService.getUserIdByLoginName(userBean.getLoginName()));
		model.put("article", article);
		
		return "auditArticle";
	}
	
	@RequestMapping(value = "/article/doAudit", method = { RequestMethod.GET, RequestMethod.POST })
	public String doAudit(long id, Audit audit, HttpServletRequest request, ModelMap model) {
		try {
			articleService.auditArticle(id, audit);
		} catch (JiongException e) {
			logger.error("doAudit failure：", e);
		}
		
		return this.audit(request, model);
	}
	
	@RequestMapping(value = "/article/comment/{id}", method = { RequestMethod.GET, RequestMethod.POST })
	public String comment(@PathVariable("id") long id, PageBean pageBean, HttpServletRequest request, ModelMap model) {
		
		model.put("isAimComment", true);
		return this.article(id, pageBean, request, model);
	}
	
	@RequestMapping(value = "/article/{id}", method = { RequestMethod.GET, RequestMethod.POST })
	public String article(@PathVariable("id") long id, PageBean pageBean, HttpServletRequest request, ModelMap model) {
		Map<String, Object> articleMap = articleService.getPackageArticleById(id);
		Page page = commentService.getCommentPageList(pageBean, new Comment());
		
		model.put("articleMap", articleMap);
		model.put("commentMapList", page.getlistResult());
		model.put("pageBean", page.getPageBean());
		
		return "article";
	}

}
